package db

import (
	"context"
	"gorm.io/gorm"
	"jmicro/app/jshop/api/internal/data"
	data2 "jmicro/app/jshop/api/internal/domain/do"
	"jmicro/jmicro/code"
	metav1 "jmicro/pkg/common/meta/v1"
	"jmicro/pkg/errors"
)

type user struct {
	db *gorm.DB
}

func (u *user) List(ctx context.Context, orderby []string, opts metav1.ListMeta) (*data2.UserListDO, error) {
	ret := data2.UserListDO{}
	//分页
	var limit, offset int
	if opts.PageSize == 0 {
		limit = 10
	} else {
		limit = opts.PageSize
	}
	if opts.Page > 0 {
		offset = (opts.Page - 1) * limit
	}
	//排序
	query := u.db
	for _, value := range orderby {
		//坑：如果db改掉了？
		//u.db=u.db.Order(value)
		query = query.Order(value)
	}
	//查询 - 发起多个请求
	d := query.Offset(offset).Limit(limit).Find(&ret.Items).Count(&ret.TotalCount)
	if d.Error != nil {
		return nil, errors.WithCode(code.ErrDatabase, d.Error.Error())
	}
	return &ret, nil
}

var _ data.UserData = &user{}

func NewUsers(db *gorm.DB) data.UserData {
	return &user{db: db}
}

func (u *user) Create(ctx context.Context, user *data2.UserDO) error {
	//TODO implement me
	panic("implement me")
}

func (u *user) Update(ctx context.Context, user *data2.UserDO) error {
	//TODO implement me
	panic("implement me")
}

func (u *user) Get(ctx context.Context, userID uint64) (*data2.UserDO, error) {
	var userInfo data2.UserDO
	if err := u.db.Where("id = ?", userID).First(&userInfo).Error; err != nil {
		return nil, errors.WithCode(code.ErrDatabase, err.Error())
	}
	return &userInfo, nil
}

func (u *user) GetByMobile(ctx context.Context, mobile string) (*data2.UserDO, error) {
	//TODO implement me
	panic("implement me")
}

func (u *user) CheckPassWord(ctx context.Context, password, encryptedPwd string) error {
	//TODO implement me
	panic("implement me")
}
